<template>
  <view class="honor-task">
    <view class="header-view">
      <up-icon name="arrow-left" color="#fff" @tap="handleBackNavBtnClick" />
      <view class="score-view">
        <text class="score" @tap="toMyRightsScore">
          {{ score }}
        </text>
        权益分
        <!-- <text @tap="get1688NavParams" class="exchange">
          去兑换
          <up-icon
            name="arrow-right"
            :size="rpx2px(18)"
            color="#ffffff"
            :width="rpx2px(31)"
          ></up-icon>
        </text> -->
      </view>
      <view v-if="!isTodaySigned" class="sign-btn" @tap="handleSignInBtnClick">
        立即签到
      </view>
      <view v-else class="signed-btn"> 已签到 </view>
      <view class="sign-btn exchange" @tap="get1688NavParams"> 立即兑换 </view>
    </view>
    <view class="sign-box">
      <view class="title">
        <view class="left">
          <text class="left-top"> 已连续签到{{ signDays }}天 </text>
          <text class="left-bottom">
            {{ signTips }}
          </text>
        </view>
        <text class="right" @tap="goToSignInDesc"> 签到说明？ </text>
      </view>
      <view class="sign-card">
        <template v-for="(item, idx) in dateList" :key="idx">
          <sign-date-card :date="item.date" :is-signed="item.isSigned" />
        </template>
      </view>
    </view>
    <view class="daily-task-card">
      <text class="title"> 日常任务 </text>
      <view class="task-list">
        <view class="task" v-for="(task, idx) in dailyTaskList" :key="idx">
          <img :src="task.icon" alt="" class="task-icon" />
          <view class="task-desc">
            <text class="task-desc__title">
              {{ task.title }}
            </text>
            <text class="task-desc__content">
              {{ task.desc }}
            </text>
          </view>
          <view
            v-if="task.isCompleted"
            class="btn"
            @tap="handleToCompleteBtnClick(task)"
          >
            去完成
          </view>
          <view v-else class="btn"> 已完成 </view>
        </view>
      </view>
    </view>
  </view>
</template>
<script setup>
import { ref, getCurrentInstance } from "vue";
import SignDateCard from "@/package_task/components/sign-date-card.vue";
import {
  getSignAwardModelApi,
  getUserDailyTaskInfoApi,
  getUserSignInInfoApi,
  userSignInAPi,
} from "@/api/task";
import { get1688NavParamsApi } from "@/api/shopping";
import { onShow } from "@dcloudio/uni-app";
import { customNav } from "@/utils/customNav";
import { rpx2px } from "../../utils/utils";
const handleBackNavBtnClick = () => {
  uni.switchTab({
    url: "/pages/index/index",
  });
};
const { proxy } = getCurrentInstance();
//用户权益分
const score = ref(0);
// 连续签到天数
const signDays = ref(0);

// 今天是否签到
const isTodaySigned = ref(false);
const signTips = ref("");
/**
 * 立即签到按钮点击事件监听
 * @returns {Promise<void>}
 */
const handleSignInBtnClick = async () => {
  const res = await userSignInAPi();
  const { code, data } = res;
  if (code === 200) {
    await uni.showToast({
      title: "签到成功",
      icon: "success",
    });
    isTodaySigned.value = true;
    getSignAwardModel();
    generalDatesList();
  }
};
// 跳转程序
const get1688NavParams = async () => {
  const res = await get1688NavParamsApi();
  const { code, data } = res;
  if (code === 200) {
    console.log("测试半瓶跳转参数code", data.code);
    // #ifdef H5 || APP-PLUS
    openMiniProgram(data.code, data.phone);
    // #endif

    // #ifdef  MP-WEIXIN
    // uni.openEmbeddedMiniProgram({
    uni.navigateToMiniProgram({
      appId: "wx90337e70657a6d17",
      path: "pages/index/index",
      envVersion: "release",
      extraData: {
        authCode: data.code,
        mobile: data.phone,
      },
    });
    // #endif
  }
};
const toMyRightsScore = () => {
  customNav("my-rights-scores");
};
function openMiniProgram(code, phone) {
  let data = {
    targetId: "gh_f19b19cb63b7",
    paramsStr: `pages/index/index?mobile=${phone}&authCode=${code}`,
    // paramsStr: `pages/index/index`,
    type: 0,
  };
  window.mobile.jsCallOpenSmallProgram(JSON.stringify(data));

  // // 这里的参数需要根据实际的小程序码和参数来设置
  // const url = "wx90337e70657a6d17"; // 小程序的码，需要在微信公众平台获取
  // const param = "pages/index/index"; // 需要传递给小程序的参数，如path等

  // // 调用微信提供的API
  // wx.miniProgram.navigateTo({
  //   url: `${url}?query=` + param, // 这里的URL需要根据实际传递参数调整
  // });
}
/**
 * 跳转到签到说明
 */
const goToSignInDesc = () => {
  customNav("sign-in-desc");
};

//签到列表
const signInList = ref([]);
/**
 * 获取签到模板
 * @returns {Promise<void>}
 */
const getSignAwardModel = async () => {
  const res = await getSignAwardModelApi();
  const { code, data } = res;
  if (code === 200) {
    isTodaySigned.value = !data.isSignIn;
    signTips.value = data.totalList[0].detail;
    score.value = parseInt(data.integral);
    signInList.value = data.continuous;
    await getUserSignInInfo();
  }
};
/**
 * 获取用户签到数据
 * @returns {Promise<void>}
 */
const getUserSignInInfo = async () => {
  const res = await getUserSignInInfoApi();
  const { code, data } = res;
  if (code === 200) {
    signDays.value = data?.totalDays;
    generalDatesList();
  }
};

// 日期
const dateList = ref([]);
/**
 * 生成签到日期
 */
const generalDatesList = () => {
  dateList.value = [];
  let curDate = new Date();
  let curDay = curDate.getDate();
  let curMonth = curDate.getMonth() + 1;
  for (let i = -3; i <= 3; i++) {
    let newDate = new Date(curDate);
    newDate.setDate(curDay + i);
    let day = newDate.getDay();
    let month = newDate.getMonth() + 1;
    var daysOfWeek = [
      "星期一",
      "星期二",
      "星期三",
      "星期四",
      "星期五",
      "星期六",
      "星期天",
    ];
    dateList.value.push({
      date: daysOfWeek[i + 3],
      isSigned: signInList.value[i + 3].signInState === 0,
    });
  }
};

const dailyTaskList = ref([
  {
    icon: "https://minio.gzryzl.com/huatai/2024-07-25/1721888401447rongyuku.png",
    title: "搜一搜荣誉库",
    desc: "获得5权益分",
    name: "honorarySearch",
  },
  /* #ifdef H5 */
  {
    icon: "https://minio.gzryzl.com/huatai/2024-07-25/1721892728419yuanyuzhou.png",
    title: "逛元宇宙",
    desc: "获得5权益分",
    name: "visitMetaverse",
  },
  /* #endif */
  {
    icon: "https://minio.gzryzl.com/huatai/2024-07-25/1721892541014AI.png",
    title: "政策AI咨询",
    desc: "获得5权益分",
    name: "policyAi",
  },
]);

const getUserDailyTaskInfo = async () => {
  const res = await getUserDailyTaskInfoApi();
  const { code, data } = res;
  if (code === 200) {
    for (let key in data) {
      dailyTaskList.value.forEach((item) => {
        if (item.name === key) {
          item.isCompleted = !data[key];
        }
      });
    }
  }
};
const handleToCompleteBtnClick = (task) => {
  switch (task.name) {
    case "honorarySearch":
      customNav("/package_honour/pages/honour/index");
      break;
    case "policyAi":
      customNav("/package_customer_service/pages/customer-service/index");
      break;
    case "visitMetaverse":
      proxy.$unity3dGlobal();
      break;
  }
};
onShow(() => {
  getSignAwardModel();
  getUserDailyTaskInfo();
});
</script>
<style lang="less" scoped>
@import url(../lib/index.less);
</style>